package com.gowants.pems.util;
import java.security.MessageDigest;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

public class AESForNodejs {
	public static final String DEFAULT_CODING = "utf-8";
	 
	/**
	 * 解密
	 * @author ylw
	 * @date 2020-10-15
	 * @param encrypted
	 * @param seed
	 * @return
	 * @throws Exception
	 */
	public static String decrypt(String encrypted, String seed) throws Exception {
		byte[] keyb = seed.getBytes(DEFAULT_CODING);
		MessageDigest md = MessageDigest.getInstance("MD5");
		byte[] thedigest = md.digest(keyb);
		SecretKeySpec skey = new SecretKeySpec(thedigest, "AES");
		Cipher dcipher = Cipher.getInstance("AES");
		dcipher.init(Cipher.DECRYPT_MODE, skey);

		byte[] clearbyte = dcipher.doFinal(toByte(encrypted));
		return new String(clearbyte);
	}

	/**
	 * 加密
	 * @author YLW
	 * @date 2020-10-15
	 * @param content
	 * @param key
	 * @return
	 * @throws Exception
	 */
	public static String encrypt(String content, String key) throws Exception {
		byte[] input = content.getBytes(DEFAULT_CODING);

		MessageDigest md = MessageDigest.getInstance("MD5");
		byte[] thedigest = md.digest(key.getBytes(DEFAULT_CODING));
		SecretKeySpec skc = new SecretKeySpec(thedigest, "AES");
		 // 算法/模式/补码方式
		Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
		cipher.init(Cipher.ENCRYPT_MODE, skc);

		byte[] cipherText = new byte[cipher.getOutputSize(input.length)];
		int ctLength = cipher.update(input, 0, input.length, cipherText, 0);
		ctLength += cipher.doFinal(cipherText, ctLength);

		return parseByte2HexStr(cipherText);
	}

	/**
	 * 字符串转字节数组
	 * @author YLW
	 * @date 2020-10-15
	 * @param hexString
	 * @return
	 */
	private static byte[] toByte(String hexString) {
		int len = hexString.length() / 2;
		byte[] result = new byte[len];
		for (int i = 0; i < len; i++) {
			result[i] = Integer.valueOf(hexString.substring(2 * i, 2 * i + 2), 16).byteValue();
		}
		return result;
	}

	/**
	 * 字节转16进制数组
	 * @author YLW
	 * @date 2020-10-15
	 * @param buf
	 * @return
	 */
	private static String parseByte2HexStr(byte buf[]) {
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < buf.length; i++) {
			String hex = Integer.toHexString(buf[i] & 0xFF);
			if (hex.length() == 1) {
				hex = '0' + hex;
			}
			sb.append(hex);
		}
		return sb.toString();
	}
	 public static void main(String[] args) {
		try {
		 String value="9e4b639d74ebfd36b1756c29823f7c993caba871fc3d21828711ac1e7c27ac6765ba48b69cbfc1d2adbf5ee0834c15e5761f41a8cad311e0cdd0c782133e3316d287976ee0d8ffdd74fa473f4094f14e24e9fbb91c8343ab2b4335a6eb7217fe49989aeabfc348393c50ff91c97b2a90";
		
		String key ="Wo1WGW7Rcn";
		
	    String jm=decrypt(value,key);
	    
	    System.out.println("解密结果:"+jm);
		}
		catch(Exception ex) {}
	 }
	

}
